import { Component, Input, OnInit } from '@angular/core';
import { FetchService } from '../../../../core/net/fetch.service';
import * as _ from 'lodash';
import * as moment from 'moment';
import { OneMapService } from '../../../one-map/one-map.service';
import { FormBuilder, FormGroup } from '@angular/forms';
import { forkJoin } from 'rxjs';
import { NzMessageService } from 'ng-zorro-antd';
import { format, startOfMonth, endOfMonth, subMonths } from 'date-fns';
import { UtilService } from 'src/app/core/util/util.service';

const eigenvalues: any[] = [
    '最高水位',
    '最低水位',
    '平均水位',
    '最高流量',
    '最低流量',
    '平均流量'
];
const eigenReserviorvalues: any[] = [
    '最高水位',
    '最低水位',
    '平均水位',
    '最高入库流量',
    '最低入库流量',
    '平均入库流量',
    '最高出库流量',
    '最低出库流量',
    '平均出库流量'
];
const eigenKeys: any[] = [
    'max_Water_Height',
    'min_Water_Height',
    'avg_Water_Height',
    'max_flux',
    'min_flux',
    'avg_flus'
];
const eigenReserviorKeys: any[] = [
    'max_Height_Inside',
    'min_Height_Inside',
    'avg_Height_Inside',
    'max_Flux_Income',
    'min_Flux_Income',
    'avg_Flux_Income',
    'max_Flux_Out',
    'min_Flux_Out',
    'avg_Flux_Out'
];

@Component({
    selector: 'app-hr-single-statistics',
    templateUrl: './hr-single-statistics.component.html',
    styleUrls: ['./hr-single-statistics.component.scss', '../hr-statistics.component.scss']
})
export class HrSingleStatisticsComponent implements OnInit {

    listData = [];
    stadiaCode: string; //  当前测站编码
    stationName: string;
    stationType: string;    // ‘3’-水库 ‘7’-河道
    topDateModal = [startOfMonth(subMonths(new Date(), 1)), new Date()];    //  顶部日期选择 默认上月至今
    topDateRanges = {
        '昨日': [
            moment().subtract(1, 'days').valueOf(),
            moment().subtract(1, 'days').valueOf()
        ],
        '3日': [
            moment().subtract(3, 'days').valueOf(),
            new Date()
        ],
        '7日': [
            moment().subtract(7, 'days').valueOf(),
            new Date()
        ],
        '本月': [
            moment().startOf('month').valueOf(),
            new Date()
        ],
        '上月': [
            moment().subtract(1, 'months').startOf('month').valueOf(),
            moment().subtract(1, 'months').endOf('month').valueOf()
        ],
        '近3月': [
            moment().subtract(3, 'months').startOf('month').valueOf(),
            new Date()
        ]
    };
    processOpt: any = {
        toolbox: {
            show: true,
            feature: {
                saveAsImage: {
                    show: true,
                    excludeComponents: ['toolbox'],
                    pixelRatio: 2
                }
            }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                animation: false,
                label: {
                    backgroundColor: '#505765'
                }
            }
        },
        legend: {
            data: ['水位', '流量'],
            bottom: 10
        },
        xAxis: {
            type: 'category',
            data: []
        },
        yAxis: [
            {
                name: '水位(m)',
                type: 'value'
            },
            {
                name: '流量(m³/s)',
                type: 'value'
            }
        ],
        series: [
            {
                name: '水位',
                type: 'line',
                smooth: true,
                data: []
            },
            {
                name: '流量',
                type: 'line',
                yAxisIndex: 1,
                smooth: true,
                data: []
            }
        ]
    };
    processOptChange: any = {};
    processEchartsIntance: any;
    waterLevelDateModal = [startOfMonth(subMonths(new Date(), 1)), new Date()];
    featureForm: FormGroup;

    /*****************  旬月特征值对比  *********************/
    eigenValues: any[] = eigenvalues;

    eigenKeys: any[] = eigenKeys;
    monthSelectedIdx: number = 0;
    timeTypes: any[] = [{
        label: '旬',
        value: '1'
    }, {
        label: '月',
        value: '2'
    }];
    monthType = '2';
    curYear: string = '2020';
    year1: Date = new Date('2018');
    year2: Date = new Date('2019');
    monthData: any = {};
    monthOpt: any = {
        toolbox: {
            show: true,
            feature: {
                saveAsImage: {
                    show: true,
                    excludeComponents: ['toolbox'],
                    pixelRatio: 2
                }
            }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: [],
            bottom: 0
        },
        grid: {
            top: '10%',
            bottom: '8%',
            left: '6%',
            right: '4%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
        },
        yAxis: {
            name: '流量(m³/s)',
            type: 'value'
        },
        series: []
    };
    monthOptChange: any = {};
    /******************* end *******************/

    /******************* 监测数据 *******************/
    tableData = [];
    pageNum = 1;
    pageSize = 25;
    /******************* end *******************/


    /******************* 历史同期对比 *******************/
    hType: number = 0;
    historyTypes: any[] = ['水位', '流量'];
    historyKeys: any[] = ['heightInside', 'fluxIncome'];
    historyYear1: Date = new Date('2018');
    historyYear2: Date = new Date('2019');
    historyBegin: Date = new Date('1970-1-1');
    historyEnd: Date = new Date('1970-10-7');
    historyLists: any[] = [];
    historyOpt: any = {
        toolbox: {
            show: true,
            feature: {
                saveAsImage: {
                    show: true,
                    excludeComponents: ['toolbox'],
                    pixelRatio: 2
                }
            }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: ['2018', '2019']
        },
        xAxis: {
            type: 'category',
            data: []
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: '2018',
                type: 'line',
                data: []
            },
            {
                name: '2019',
                type: 'line',
                data: []
            }
        ]
    };
    historyOptChange: any = {};

    @Input()
    get dateModal() {
        // this.queryInfo();
        return this._dateModal;
    }

    set dateModal(val) {
        this._dateModal = val;
        if (this.stadiaCode) {
            this.queryInfo();
        }
    }

    // tslint:disable-next-line:variable-name
    _dateModal = [startOfMonth(new Date()), new Date()];

    /******************* end *******************/
    constructor(private fetchService: FetchService,
                private mapService: OneMapService,
                private message: NzMessageService,
                private fb: FormBuilder,
                private util: UtilService) {
        this.featureForm = this.fb.group({
            warningLevel: [''],
            securityLevel: [''],
            max: [''],
            min: [''],
            maxTime: [''],
            minTime: [''],
            avg: [''],
            mid: [''],
            lastAvg: [''],
            lastMid: [''],
            compareWarning: [''],
            compareSecure: ['']
        });
    }

    ngOnInit() {
        this.fetchService.post<any>('wrs/wrsBrstadia/list', {}).subscribe(res => {
            // console.log(res);
            this.listData = res['list'];
            this.selectedAreaChanged(this.listData[0].stadiaCode);
        });
    }

    selectedAreaChanged(code): void {
        // console.log(code);
        const selectedArea = _.find(this.listData, item => {
            return item.stadiaCode === code;
        });
        this.stationName = selectedArea.stadiaName;
        this.stadiaCode = code;
        this.stationType = selectedArea.stadiaType;
        this.eigenValues = this.stationType === '7' ? eigenvalues : eigenReserviorvalues;
        this.eigenKeys = this.stationType === '7' ? eigenKeys : eigenReserviorKeys;
        this.monthSelectedIdx = 0;
        this.queryInfo();
    }

    queryInfo(): void {
        // console.log(this.topDateModal);
        this.waterLevelDateModal = this.dateModal;
        this.onQueryProcessList();
        this.onQueryMonthList();
        this.getMonitorTableData();
    }

    getProcessListSection() {
        const url = this.stationType === '7' ? 'base/wrsBrwaterRiver/queryProcessLinList' : 'base/wrsBrwaterReservior/queryProcessLinList';
        const params = {
            stadiaCode: this.stadiaCode,
            beginTime: moment(this.waterLevelDateModal[0]).format('YYYY-MM-DD'),
            endTime: moment(this.waterLevelDateModal[1]).format('YYYY-MM-DD'),
            pageSize: 100000
        };
        return this.fetchService.post(url, params);
    }

    getMonthListSection() {
        const url = this.stationType === '7' ? 'base/wrsBrwaterRiver/queryMonthList' : 'base/wrsBrwaterReservior/queryMonthList';
        const params = this.stationType === '7' ?
            {
                stadiaCode: this.stadiaCode,
                year: this.curYear,
                history: `${this.year1.getFullYear()},${this.year2.getFullYear()}`,
                type: this.monthType
            } : {
                stadiaCode: this.stadiaCode,
                year: this.curYear,
                beginTime: this.year1.getFullYear(),
                endTime: this.year2.getFullYear(),
                type: this.monthType
            };
        return this.fetchService.post(url, params);
    }

    onQueryProcessList() {
        this.getProcessListSection().subscribe(res => {
            const list = res['list'];
            const legendData = this.stationType === '7' ? ['水位', '流量'] : ['水位', '入库流量', '出库流量'];
            const commonOpt = {
                toolbox: {
                    show: true,
                    feature: {
                        saveAsImage: {
                            show: true,
                            excludeComponents: ['toolbox'],
                            pixelRatio: 2
                        }
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                        animation: false,
                        label: {
                            backgroundColor: '#505765'
                        }
                    }
                },
                legend: {
                    data: legendData,
                    bottom: 10
                },
                yAxis: [
                    {
                        name: '水位(m)',
                        type: 'value'
                    },
                    {
                        name: '流量(m³/s)',
                        type: 'value'
                    }
                ],
                xAxis: {
                    data: list.map(item => {
                        return item['meaTime'];
                    })
                }
            };
            let propsList = [];
            if (this.stationType === '3') {
                propsList = ['heightInside', 'fluxIncome', 'fluxOut'];
            } else {
                propsList = ['waterHeight', 'flux'];
            }
            let whMax;
            let whMin;
            let flowMax;
            let flowMin;
            const reservoirData = legendData.map((o, idx) => {
                const seriesData = [];
                list.forEach(item => {
                    seriesData.push(item[propsList[idx]]);
                });
                if (idx == 0) {
                    whMax = this.util.max(seriesData);
                    whMin = this.util.min(seriesData);
                } else if (idx == 1) {
                    flowMax = this.util.max(seriesData);
                    flowMin = this.util.min(seriesData);
                } else {
                    flowMax = this.util.max(seriesData.concat(flowMax));
                    flowMin = this.util.min(seriesData.concat(flowMin));
                }
                return {
                    name: o,
                    type: 'line',
                    smooth: true,
                    yAxisIndex: idx > 0 ? 1 : 0,
                    markPoint: {
                        // symbol: 'diamond',
                        symbolSize: 30,
                        data: [
                            {
                                type: 'max',
                                name: '最大'
                            },
                            {
                                name: '最小',
                                type: 'min'
                            },
                        ],
                        label: {
                            normal: {
                                formatter: (params) => {
                                    return `${params.name}: ${params.value}`;
                                }
                            }
                        }
                    },
                    data: seriesData
                };
            });
            this.processOptChange = {
                ...commonOpt, ...{
                    series: reservoirData
                },
                yAxis: [
                    {
                        name: "水位(m)",
                        type: "value",
                        min: Math.floor(this.calcYAxisData('min', whMax, whMin)),
                        max: Math.ceil(this.calcYAxisData('max', whMax, whMin)),
                    },
                    {
                        name: "流量(m³/s)",
                        type: "value",
                        min: Math.floor(this.calcYAxisData('min', flowMax, flowMin)),
                        max: Math.ceil(this.calcYAxisData('max', flowMax, flowMin)),
                    }
                ]
            };
            this.processEchartsIntance.setOption(this.processOptChange, true);

        });
    }

    private calcYAxisData(type: string, max: number, min: number): number {
        if (type === 'max') {
            return max + (max - min) / 2;
        } else if (type === 'min') {
            return (min - (max - min)) >= 0 ? +(min - (max - min)) : 0;
        }
    }

    getMonitorTableData(): void {
        const url = this.stationType === '7' ? 'base/wrsBrwaterRiver/queryMonitorList' : 'base/wrsBrwaterReservior/queryMonitorList';
        const params = {
            stadiaCode: this.stadiaCode,
            beginTime: moment(this.waterLevelDateModal[0]).format('YYYY-MM-DD'),
            endTime: moment(this.waterLevelDateModal[1]).format('YYYY-MM-DD')
        };
        this.fetchService.post(url, params).subscribe(res => {
            const data = Object.values(res)[0];
            data.forEach(item => {
                item['date'] = moment(item['Mea_Time']).format('YYYY-MM-DD');
                item['time'] = moment(item['Mea_Time']).format('HH:mm:ss');
            });
            this.tableData = data;
            console.log(this.tableData);
        });
    }

    processChartInit(ec) {
        this.processEchartsIntance = ec;
    }

    onQueryMonthList() {
        this.getMonthListSection().subscribe((data: any) => {
            this.monthData = data;
            this.changeMonthChart();
        });
    }

    changeMonthChart() {
        const data = this.monthData;
        const keys: any[] = Object.keys(data);
        this.monthOptChange = {
            legend: {
                data: keys.map(k => {
                    return k == 'historyYear' ? '历史年段' : k;
                })
            },
            yAxis: {
                name: this.monthSelectedIdx < 3 ? '水位（m）' : '流量（m³/s）'
            },
            xAxis: {
                axisLabel: {
                    interval: 0
                },
                data: this.monthData[keys[0]].map(item => {
                    if (this.monthType === '1') {
                        return item.m;
                    } else {
                        return item['mea_time'] + '月';
                    }
                })
            },
            series: keys.map(key => {
                return {
                    name: key == 'historyYear' ? '历史年段' : key,
                    type: 'bar',
                    barWidth: '20%',
                    data: data[key].map(item => {
                        return item[this.eigenKeys[this.monthSelectedIdx]];
                    })
                };
            })
        };
    }

    onChangeHistory(dates) {
        this.historyBegin = dates[0];
        this.historyEnd = dates[1];
    }

    getHistoryListSection(date) {
        const url = this.stationType === '7' ? 'base/wrsBrwaterRiver/queryProcessLinList' : 'base/wrsBrwaterReservior/queryProcessLinList';
        const params = this.stationType === '7' ?
            {
                stadiaCode: this.stadiaCode,
                beginTime: `${moment(date).year()}-${moment(this.historyBegin).format('MM-DD')}`,
                endTime: `${moment(date).year()}-${moment(this.historyEnd).format('MM-DD')}`
            } : {
                stadiaCode: this.stadiaCode,
                beginTime: `${moment(date).year()}-${moment(this.historyBegin).format('MM-DD')}`,
                endTime: `${moment(date).year()}-${moment(this.historyEnd).format('MM-DD')}`
            };
        return this.fetchService.post(url, params);
    }

    onQueryHistory() {
        const history1 = this.getHistoryListSection(this.historyYear1);
        const history2 = this.getHistoryListSection(this.historyYear2);
        forkJoin(history1, history2).subscribe(datas => {
            this.historyLists = datas.map(data => {
                return data['list'];
            });
            this.changeHistoryChart();
        });
    }

    changeHistoryChart() {
        const lists = this.historyLists;
        if (!lists[0].length || !lists[1].length) {
            this.message.error('---无数据---');
            return;
        }
        const xAxisData = lists[0].map(item => {
            return item.meaTime.substr(5);
        });
        const legendData: any[] = [];
        const seriesData: any[] = [];
        lists.map(list => {
            const year = list[0].meaTime.substr(0, 4);
            legendData.push(year);
            seriesData.push({
                name: year,
                type: 'line',
                data: list.map(item => {
                    return item[this.historyKeys[this.hType]];
                })
            });
        });
        this.historyOptChange = {
            legend: {
                data: legendData
            },
            xAxis: {
                data: xAxisData
            },
            series: seriesData
        };
        // console.log(this.historyOptChange);
    }

    private getItemValues(list, key) {
        return list.map(i => {
            return i[key] || 0;
        });
    }
}
